package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class NavServiceImpl implements INavService {
    @Override
    public List<NavModel> getNavModelList() {
        Timer timer = new Timer();
        final List<NavModel>[] list = new List[]{new ArrayList<>()};
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                list[0] = getData();
            }
        }, 60 * 10 * 1000,60 * 10 * 1000);

        return list[0];

    }

    private List<NavModel> getData() {
        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        NavDao navDao = new NavImpl();
        if (jedis.exists("navHref")) {
            List<String> navHrefList = jedis.lrange("navHref", 0, -1);
            for (int i = 0; i < navHrefList.size(); i++) {
                NavModel navModel = new NavModel();
                navModel.setHref(navHrefList.get(i));
                navModel.setName(jedis.lindex("navName", i));
                list.add(navModel);
            }
        } else {
            list = navDao.getList();//查询数据库，保存到redis
//            String String
//            Object Object
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("navHref", list.get(i).getHref());
                jedis.rpush("navName", list.get(i).getName());
            }
        }
        return list;
    }

    public int add(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int result = navDao.add(navModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("navHref");
            jedis.del("navName");
        }
        return result;
    }
}
